#include "emojisimpleloadermainwindow.h"
#include "ui_emojisimpleloadermainwindow.h"

#include <QDir>
#include <QSortFilterProxyModel>
#include <QStyledItemDelegate>

#include <src/gui/emojidelegate.h>

EmojiSimpleLoaderMainWindow::EmojiSimpleLoaderMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::EmojiSimpleLoaderMainWindow)
{
    ui->setupUi(this);

#ifdef EXAMPLE_DATA_DIRECTORY
    QDir data(EXAMPLE_DATA_DIRECTORY);
    auto entrys = data.entryList(QDir::Files);

    QStringList disguisedGifs;
    for (int i = 0; i < entrys.count(); ++i) {
        entrys[i].prepend(EXAMPLE_DATA_DIRECTORY);
        if (isActuallyGif(entrys[i])) {
            disguisedGifs << entrys[i];
        }
    }

    ui->statusbar->showMessage(QString("从 data 目录中获取到: %1 个文件(%2个gif)")
                                   .arg(entrys.count())
                                   .arg(disguisedGifs.count()));
    slistmodel.setStringList(entrys);
#endif

    // 2. 设置自定义代理模型
//    GifFilterProxyModel *
    proxymodel = new GifFilterProxyModel;
    proxymodel->setSourceModel(&slistmodel);
    proxymodel->setDisguisedGifs(disguisedGifs); // 传入伪装文件列表

    ui->emoji_list->setModel(proxymodel);
}

EmojiSimpleLoaderMainWindow::~EmojiSimpleLoaderMainWindow()
{
    delete ui;
}

void EmojiSimpleLoaderMainWindow::resizeEvent(QResizeEvent *event)
{
    emit proxymodel->layoutChanged();
}

void EmojiSimpleLoaderMainWindow::on_emoji_delegate_stateChanged(int arg1)
{
    auto delegate = ui->emoji_list->itemDelegate();

    if (arg1 == Qt::CheckState::Checked) {
        ui->emoji_list->setViewMode(QListView::IconMode);
        ui->emoji_list->setItemDelegate(new EmojiDelegate());
    } else {
        ui->emoji_list->setViewMode(QListView::ListMode);
        ui->emoji_list->setItemDelegate(new QStyledItemDelegate());
    }
    if (delegate) {
        delegate->deleteLater();
        // emit proxymodel->layoutChanged();
    }
}

void EmojiSimpleLoaderMainWindow::on_emoji_gifs_stateChanged(int arg1)
{
    proxymodel->setFilterEnabled(arg1 == Qt::CheckState::Checked);
}

bool EmojiSimpleLoaderMainWindow::isActuallyGif(const QString &filePath) const
{
    // 检查文件扩展名和实际内容
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        return false;
    }

    // 读取文件头检查GIF签名
    QByteArray header = file.read(6);
    file.close();

    // GIF文件头可能是"GIF87a"或"GIF89a"
    // return header.startsWith("GIF87a") || header.startsWith("GIF89a");
    bool isGif = header.startsWith("GIF87a") || header.startsWith("GIF89a");
    return isGif;
}

